package thread;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

/*核⼼操作为 submit, 将任务加⼊线程池中
• 使⽤ Worker 类描述⼀个⼯作线程. 使⽤ Runnable 描述⼀个任务.
• 使⽤⼀个 BlockingQueue 组织所有的任务
• 每个 worker 线程要做的事情: 不停的从 BlockingQueue 中取任务并执⾏.
• 指定⼀下线程池中的最⼤线程数 maxWorkerCount; 当当前线程数超过这个最⼤值时, 就不再新增线程了*/

// 创建线程池
class MyTreadPoll {
    // 创建阻塞队列,将任务存至队列中
    private BlockingDeque<Runnable> queue = new LinkedBlockingDeque<>();

    // 初始化线程池,并设置线程池的固定线程数量
    public MyTreadPoll(int n) {
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
                while (true) {
                    try {
                        Runnable runnable = queue.take();
                        runnable.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            t.start();
        }
    }

    // 使用submit方法来添加任务
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }
}

public class test20 {
    public static void main(String[] args) throws InterruptedException {
        MyTreadPoll myTreadPoll = new MyTreadPoll(5);
        for (int i = 0; i < 10000; i++) {
            int id = i;
            myTreadPoll.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " " + id + " Thread");
                }
            });
        }
    }
}
